package cn.ynu.cmrs.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import cn.ynu.cmrs.MyApplication;
import cn.ynu.cmrs.R;
import cn.ynu.cmrs.adapter.AllCourseAdapter;
import cn.ynu.cmrs.asyncTask.GetInfosTask;
import cn.ynu.cmrs.model.College;
import cn.ynu.cmrs.model.CollegeInfoHead;
import cn.ynu.cmrs.model.CollegeInfoItem;
import cn.ynu.cmrs.utils.JsonParse;
import cn.ynu.cmrs.utils.WebInterface;

import com.viewpagerindicator.TabPageIndicator;

public class AllCourse extends FragmentActivity {

	private static final String KEY_CONTENT = "AllCourse:College";

	/**
	 * Retries of request college information
	 */
	private int retryCount = 0;

	private College colleges;
	private View process;
	private View titleBar;
	private TextView titleName;

	FragmentPagerAdapter mAdapter;
	ViewPager mPager;
	TabPageIndicator mTabIndicator;

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		Log.i("onSaveInstanceState", colleges.toString());
		outState.putSerializable(KEY_CONTENT, colleges);
	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.allcourse_list);
		if (savedInstanceState != null
				&& savedInstanceState.getSerializable(KEY_CONTENT) != null) {
			colleges = (College) (savedInstanceState
					.getSerializable(KEY_CONTENT));
		}
		MyApplication.allActivity.add(this);
		prepareView();
		if (colleges == null || colleges.getItems().size() == 0) {
			new GetCollegesTask(this, R.string.fail_general, process).execute();
		} else {
			process.setVisibility(View.GONE);
			mAdapter = new AllCourseAdapter(getSupportFragmentManager(),
					colleges, AllCourse.this);
			mPager.setAdapter(mAdapter);
			mTabIndicator.setViewPager(mPager);
		}
	}

	protected void prepareView() {
		process = findViewById(R.id.progress_allcourselist);
		titleBar = findViewById(R.id.allcourse_title);
		titleName = (TextView) titleBar.findViewById(R.id.textViewTitle);
		titleName.setText(R.string.all_course);
		mPager = (ViewPager) findViewById(R.id.tabpager);
		mTabIndicator = (TabPageIndicator) findViewById(R.id.tabIndicator);
		if (colleges == null) {
			colleges = new College(new CollegeInfoHead(0),
					new ArrayList<CollegeInfoItem>(), null);
		}
		mAdapter = new AllCourseAdapter(getSupportFragmentManager(), colleges,
				AllCourse.this);
		mPager.setAdapter(mAdapter);
		mTabIndicator.setViewPager(mPager);
	}

	/**
	 * AsyncTask class, Get information of schools
	 * 
	 * @author Yasha
	 * 
	 */
	private class GetCollegesTask extends GetInfosTask<Void, College> {

		public GetCollegesTask(Activity mActivity, int mFailMsg, View mView) {
			super(mActivity, mFailMsg, mView);
		}

		@Override
		protected College doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			Map<String, String> param = new HashMap<String, String>();
			param.clear();
			param.put("interface", "getcolinf");
			String result = WebInterface.webInterface(param);
			College colleges;
			try {
				colleges = JsonParse.getCollege(result);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				colleges = new College(null, null, new String[] { "8086",
						mActivity.getString(R.string.inner_error_json) });
			}
			return colleges;
		}

		@Override
		protected void onPostExecute(College result) {
			// TODO Auto-generated method stub
			String[] status = result.getStatus();
			if (status[0].equals("0")) {
				mView.setVisibility(View.GONE);
				doStuffWithResult(result);
			} else {
				if (retryCount < 3) {
					new GetCollegesTask(AllCourse.this, R.string.fail_general,
							process).execute();
					retryCount++;
				} else {
					mView.setVisibility(View.GONE);
					failMsg(status[1]);
				}
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			mView.setVisibility(View.VISIBLE);
		}

		@Override
		protected void doStuffWithResult(College result) {
			// TODO Auto-generated method stub
			colleges = result;
			mAdapter = new AllCourseAdapter(getSupportFragmentManager(),
					colleges, AllCourse.this);
			mPager.setAdapter(mAdapter);
			mTabIndicator.setViewPager(mPager);
		}
	}

	/**
	 * Launch this Activity from the outside
	 * 
	 * @param context
	 *            context from which Activity should be started
	 */
	public static void launch(Context context) {
		Intent intent = new Intent(context, AllCourse.class);
		context.startActivity(intent);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// Capture the back button to prompt exit
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			MyApplication.promptExitApp(this);
		}
		return true;
	}
}
